﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Lilium.IO
{
    public static class StreamExtensions
    {
        public static byte[] ReadStrict(this Stream stream, byte[] buffer)
        {
            if (stream == null) throw new ArgumentNullException("stream");
            if (buffer == null) throw new ArgumentNullException("buffer");

            var bytesLeft = buffer.Length;
            var bufferOffset = 0;
            while (true)
            {
                var count = stream.Read(buffer, bufferOffset, bytesLeft);
                if (count == bytesLeft)
                    return buffer;
                else
                {
                    if (count == 0)
                        throw new IOException(string.Format("Unexcepted end of stream. Excepted more {0} bytes.", bytesLeft));
                    bytesLeft -= count;
                }
            } 
        }
    }
}
